package org.estela.vm;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.estela.comp.EstelaProgram;
import org.estela.comp.Function;
import org.estela.comp.Statement;

/**
 * 
 * @author antoniokantek
 *
 */
public class EstelaVM {

	/** */
	public PrintStream _out = System.out;
	
	/** */
	private Memory _memory = new Memory();


	/**
	 * Constructs a new <code>EstelaVM</code>.
	 */
	public EstelaVM() {
		this.reset();
	}
	
	public void reset() {
		_memory.reset();
	}
	
	public Instruction[] getFunction(String functionName) {
		return _memory.getFunction(functionName);
	}

	
	/**
	 * 
	 * @param program
	 * @return
	 * @throws EstelaVMExcpetion
	 */
	public long execute(EstelaProgram program) throws EstelaVMExcpetion {
		long t0 = System.currentTimeMillis();
		CodeGenerator generator = new CodeGenerator();
		for(Statement stmt : program.getStatements()) {
			System.out.println(">> stmt:" + stmt);
			stmt.accept(generator);
		}
		ExecutionFrame stackFrame = new ExecutionFrame(this, generator.getFrame());
		stackFrame.execute();
		return System.currentTimeMillis() - t0;
	}

}
